<template>
	<view class="calendar-wrapper">
		<view class="header" v-if="headerBar">
			<view class="pre" @click="changeMonth('pre')">上个月</view>
			<view>{{y+'年'+formatNum(m)+'月'}}</view>
			<view class="next" @click="changeMonth('next')">下个月</view>
		</view>
		<view class="week">
			<view class="week-day" v-for="(item, index) in weekDay" :key="index">{{ item }}</view>
		</view>
		<view :class="{ hide: !monthOpen }" class="content">
			<view :style="{ top: positionTop + 'rpx' }" class="days">
				<view class="item" v-for="(item, index) in dates" :key="index" @click="selectOne(item)">
					<view class="day"
						:class="{choose: choose == `${item.year}-${item.month}-${item.date}`&&item.isCurM,nolm: !item.isCurM,today: isToday(item.year, item.month, item.date),isWorkDay: isWorkDay(item.year, item.month, item.date)}">
						{{ Number(item.date) }}
					</view>
					<!-- 日期当天的标识 -->
					<view class="" v-if="isMarkDay(item.year, item.month, item.date)&&item.isCurM"></view>
					<!-- 日期上的文字个eg:出勤/签退 -->
					<view class="wenzi">
						<span v-for="(qitem,qindex) of item.infor" :key="qindex"
							:class="{chuqing:item.infor.length==1,chidao:qitem.signstatus=='迟到'}">
							{{qitem.signstatus}} <span v-if="qindex==0 && item.infor.length>1">/</span>
						</span>
					</view>
				</view>
			</view>
		</view>
		<image src="https://i.loli.net/2020/07/16/2MmZsucVTlRjSwK.png" mode="scaleToFill" v-if="collapsible"
			@click="toggle" class="weektoggle" :class="{ down: monthOpen }"></image>

		<view class="content">
			<view class="change">
				<!-- 选中日期：{{curDate}} -->
				<view class="item" @click="clockIn('上班',beonDuty)">上班签到</view>
				<view class="item" @click="clockIn('下班',offDuty)">下班签退</view>
			</view>
			<view class="time" style="text-align: left;">
				<view class="" v-if="beonList.length!=0" v-for="(i,k) in beonList" :key="k">{{i.signmode}}签到时间:
					{{i.beonTime}} ;
					{{i.beonState}}
				</view>
				<view class="" v-if="getoList.length!=0" v-for="(i,k) in getoList" :key="k">{{i.signmode}}签退时间:
					{{i.getoffTime}} ;
					{{i.getoffState}}
				</view>
			</view>
		</view>
		<view style="text-align: left;padding: 22px 20px;" @click="shuru">WiFi:{{ wifiName }}</view>
	</view>
</template>

<script>
	export default {
		name: 'ren-calendar',
		props: {
			// 星期几为第一天(0为星期日)
			weekstart: {
				type: Number,
				default: 0
			},
			// 标记的日期
			markDays: {
				type: Array,
				default: () => {
					return [];
				}
			},
			//是否展示月份切换按钮
			headerBar: {
				type: Boolean,
				default: true
			},
			// 是否展开
			open: {
				type: Boolean,
				default: true
			},
			//是否可收缩
			collapsible: {
				type: Boolean,
				default: false
			},
			//未来日期是否不可点击
			disabledAfter: {
				type: Boolean,
				default: true
			}
		},
		data() {
			return {
				weektext: ['日', '一', '二', '三', '四', '五', '六'],
				y: new Date().getFullYear(), // 年
				m: new Date().getMonth() + 1, // 月
				dates: [], // 当前月的日期数据
				positionTop: 0,
				monthOpen: true,
				choose: '',
				beonList: [],
				getoList: [],

				checkingIn_list: [],
				MAC: '',
				wifiName: '未连接WiFi',
				latitude: '',
				longitude: '',
				address: '',
				beonDuty: [],
				offDuty: [],

			};
		},
		created() {
			this.dates = this.monthDay(this.y, this.m);
			!this.open && this.toggle();


			this.fun_signinTime();
		},
		onLoad() { // 获取参数
			this.fun_signinTime();

		},
		mounted() {
			let vm = this;
			this.choose = this.getToday().date;

			let month = this.formatNum(this.m);
			this.fun_GetSign_Info(month);

			//#ifdef MP-WEIXIN
			wx.startWifi({
				success(res) {
					wx.getConnectedWifi({
						success(res) {
							console.log('获取已连接中的 Wi-Fi 信息', res)
							vm.MAC = res.wifi.BSSID
							vm.wifiName = res.wifi.SSID
						}
					})
				},
				fail(err) {
					console.log('接口调用失败的回调函数', err)
				},
				complete(e) {
					console.log('接口调用结束的回调函数（调用成功、失败都会执行）', e)
				}
			});
			//#endif

			vm.longitude = uni.getStorageSync("location_infor").lng
			vm.latitude = uni.getStorageSync("location_infor").lat
			vm.address = uni.getStorageSync("location_infor").dizhi


		},
		computed: {
			// 顶部星期栏
			weekDay() {
				return this.weektext.slice(this.weekstart).concat(this.weektext.slice(0, this.weekstart));
			},
			height() {
				return (this.dates.length / 7) * 80 + 'rpx';
			}
		},
		methods: {
			// 上下班点击事件，新增点击弹窗选择
			clockIn(d, data) {
				let vm = this;
				// 如果没有设置多时间段的上下班，不弹窗选择
				if (data.length <= 1) {
					vm.fun_sign(d);
					return;
				}
				uni.showActionSheet({
					itemList: data,
					success: function(res) {
						let k = res.tapIndex;
						let ss = data[k].split('：')[0];
						vm.fun_sign(ss)
					}
				});

			},
			fun_sign(d) {
				let vm = this;
				console.log(d, 'signmode');
				uni.showLoading({
					title: `请稍等……`
				})
				vm.AddSign_Info(d, vm.latitude, vm.longitude, vm.address)
			},
			// 打卡接口
			AddSign_Info(d, lat, lng, address) {
				let par = {
					signmode: d,
					mac: this.wifiName, //FSTORCOH
					lat: lat, //30.64854546440972
					lng: lng, //103.99775444878472
					address: address, //四川省成都市武侯区晋阳路269-10号
					memo: '', //打卡备注
					userid: uni.getStorageSync("ID"), //用户id
					operatortype: uni.getStorageSync("gcsorQy") == "企业端" ? 'C' : 'E', //operatortype=E/C(工程师/企业)
					Linces: 'fstorch'
				}
				console.log(par, '打卡需要的参数')
				this.API.AddSign_Info(par).then((e) => {
					//返回：2已经打卡，1成功，-2设置有误，-3范围无效，0打卡失败
					let data = JSON.parse(e.substr(1, e.length - 2))
					uni.hideLoading();
					// wx.stopLocationUpdate(function(res) {
					// 	console.log('关闭了持续定位', res)
					// })
					if (data == 0) {
						this.common.fun_hint("打卡失败!")
					}
					if (data == 1) {
						this.common.fun_hint("签到成功!");
						let month = this.formatNum(this.m);
						this.fun_GetSign_Info(month);
					}
					if (data == 2) {
						this.common.fun_hint("签到失败:今日已签到~")
					}
					if (data == -2) {
						this.common.fun_hint("设置有误,请联系管理员")
					}
					if (data == -3) {
						this.common.fun_hint("范围无效!")
					}
				}).catch((err) => {
					console.log(err, 'xxx')
					uni.hideLoading();
					uni.showToast({
						title: "打卡失败,请稍后再试或者咨询管理员",
						icon: "none"
					})
				})
			},
			//查询打卡记录
			fun_GetSign_Info(month) {
				this.dates = this.monthDay(this.y, this.m);
				let vm = this;
				uni.showLoading({
					title: `加载中..`
				})
				vm.API.GetSign_Info({
					strWhere: `username = '${uni.getStorageSync("name")}'  and signtime like '${this.y}${month}%'`,
					pgindex: 1,
					pageSize: 100,
					Linces: 'fstorch',
				}).then((e) => {
					let data = JSON.parse(e.substr(1, e.length - 2));
					let mm = 0
					data.Data.forEach(j => {
						vm.dates.forEach(i => {
							// 当前显示的月份
							if (i.isCurM) {
								// 当前月份中,中接口返回的数据对应到某一天
								if (j.signtime.substr(6, 2) == i.date) {
									// 有签到信息的天 push到该天的infor(自己添加的数组)
									i.infor.push(j)
									if (i.date == this.markDayIndex) { //判断是不是当前日期
										this.beonList = [];
										this.getoList = [];
										i.infor.forEach(k => { //显示出来
											if (k.signtime.indexOf('SB') != -1) {
												let p = {
													beonTime: k.signintime,
													beonState: k.signstatus,
													signmode: k.signmode
												}
												this.beonList.push(p);

											} else {
												let pp = {
													getoffTime: k.signintime,
													getoffState: k.signstatus,
													signmode: k.signmode
												}
												this.getoList.push(pp);
											}
										})
										console.log(this.beonList, '上班', this.getoList, '下班')
									}
								}

							}

						})
					})
					uni.hideLoading();
				})
			},

			//获取能打卡的时间范围
			fun_signinTime() {
				let str = uni.getStorageSync("signvalues");
				if (!str) return;
				let td = str.split('@')[1].split(';');
				td.forEach(i => {
					if (this.common.containsNumber(i)) {
						let t = i.split('|')[1];
						console.log(t, 'zzz')
						// cheData.push(i)
						if (i.indexOf('出勤') != -1) {
							let s = i.replace('|出勤', '').split("|");

							this.beonDuty.push(s[1] + '：' + s[0]);
						}
						if (i.indexOf('签退') != -1) {
							let s = i.replace('|签退', '').split("|");
							this.offDuty.push(s[1] + '：' + s[0]);
						}
					}
				})
				console.log(td)
				console.log(this.beonDuty, '出勤', this.offDuty, '签退')
			},




			shuru() {
				uni.showModal({
					title: '提示',
					placeholderText: '输入WIFI名称',
					editable: true,
					success: (res) => {
						if (res.confirm) {
							const wi = res.content;
							if (wi == '') return;
							this.wifiName = wi;
						}
					}
				});

			},





			formatNum(num) {
				let res = Number(num);
				return res < 10 ? '0' + res : res;
			},
			getToday() {
				let date = new Date();
				let y = date.getFullYear();
				let m = date.getMonth();
				let d = date.getDate();
				let week = new Date().getDay();
				let weekText = ['日', '一', '二', '三', '四', '五', '六'];
				let formatWeek = '星期' + weekText[week];
				let today = {
					date: y + '-' + this.formatNum(m + 1) + '-' + this.formatNum(d),
					week: formatWeek
				};
				return today;
			},
			// 获取当前月份数据
			monthDay(y, month) {
				let dates = [];
				let m = Number(month);
				let firstDayOfMonth = new Date(y, m - 1, 1).getDay(); // 当月第一天星期几
				let lastDateOfMonth = new Date(y, m, 0).getDate(); // 当月最后一天
				let lastDayOfLastMonth = new Date(y, m - 2, 0).getDate(); // 上一月的最后一天
				let weekstart = this.weekstart == 7 ? 0 : this.weekstart;
				let startDay = (() => {
					// 周初有几天是上个月的
					if (firstDayOfMonth == weekstart) {
						return 0;
					} else if (firstDayOfMonth > weekstart) {
						return firstDayOfMonth - weekstart;
					} else {
						return 7 - weekstart + firstDayOfMonth;
					}
				})();
				let endDay = 7 - ((startDay + lastDateOfMonth) % 7); // 结束还有几天是下个月的
				for (let i = 1; i <= startDay; i++) {
					dates.push({
						date: this.formatNum(lastDayOfLastMonth - startDay + i),
						day: weekstart + i - 1 || 7,
						month: m - 1 >= 0 ? this.formatNum(m - 1) : 12,
						year: m - 1 >= 0 ? y : y - 1,
						infor: []
					});
				}
				for (let j = 1; j <= lastDateOfMonth; j++) {
					dates.push({
						date: this.formatNum(j),
						day: (j % 7) + firstDayOfMonth - 1 || 7,
						month: this.formatNum(m),
						year: y,
						isCurM: true, //是否当前月份,
						infor: []
					});
				}
				for (let k = 1; k <= endDay; k++) {
					dates.push({
						date: this.formatNum(k),
						day: (lastDateOfMonth + startDay + weekstart + k - 1) % 7 || 7,
						month: m + 1 <= 11 ? this.formatNum(m + 1) : 0,
						year: m + 1 <= 11 ? y : y + 1,
						infor: []
					});
				}
				// console.log(dates, '月份列表');
				return dates;
			},
			isWorkDay(y, m, d) {
				//是否工作日
				let ymd = `${y}/${m}/${d}`;
				let formatDY = new Date(ymd.replace(/-/g, '/'));
				let week = formatDY.getDay();
				if (week == 0 || week == 6) {
					return false;
				} else {
					return true;
				}
			},
			isFutureDay(y, m, d) {
				//是否未来日期
				let ymd = `${y}/${m}/${d}`;
				let formatDY = new Date(ymd.replace(/-/g, '/'));
				let showTime = formatDY.getTime();
				let curTime = new Date().getTime();
				if (showTime > curTime) {
					return true;
				} else {
					return false;
				}
			},
			// 标记日期
			isMarkDay(y, m, d) {
				let flag = false;
				for (let i = 0; i < this.markDays.length; i++) {
					let dy = `${y}-${m}-${d}`;
					if (this.markDays[i] == dy) {

						this.markDayIndex = this.markDays[i].split("-")[2]
						flag = true;
						break;
					}
				}
				return flag;
			},
			isToday(y, m, d) {
				let checkD = y + '-' + m + '-' + d;
				let today = this.getToday().date;
				if (checkD == today) {
					return true;
				} else {
					return false;
				}
			},
			// 展开收起
			toggle() {
				this.monthOpen = !this.monthOpen;
				if (this.monthOpen) {
					this.positionTop = 0;
				} else {
					let index = -1;
					this.dates.forEach((i, x) => {
						this.isToday(i.year, i.month, i.date) && (index = x);
					});
					this.positionTop = -((Math.ceil((index + 1) / 7) || 1) - 1) * 80;
				}
			},
			// 点击回调
			selectOne(i, event) {
				let date = `${i.year}-${i.month}-${i.date}`;
				let selectD = new Date(date).getTime();
				let curTime = new Date().getTime();
				let week = new Date(date).getDay();
				let weekText = ['日', '一', '二', '三', '四', '五', '六'];
				let formatWeek = '星期' + weekText[week];
				let response = {
					date: date,
					week: formatWeek
				};
				if (!i.isCurM) {
					console.log('不在当前月范围内');
					return false;
				}
				if (selectD > curTime) {
					/* if (this.disabledAfter) {
						console.log('未来日期不可选');
						return false;
					} else {
						this.choose = date;
						this.$emit('onDayClick', response);
					} */
					this.choose = date;
					this.$emit('onDayClick', response);
				} else {
					this.choose = date;
					this.$emit('onDayClick', response);
				}
				// console.log(response,'当前日期');
				this.getoList = [];
				this.beonList = [];
				/* this.beonTime = '';
				this.getoffTime = '';
				this.beonState = '';
				this.getoffState = ''; */
				console.log(i.infor, '当前日期')
				i.infor.forEach(k => {
					if (k.signtime.indexOf('SB') != -1) {
						let pp = {
							beonTime: k.signintime,
							beonState: k.signstatus,
							signmode: k.signmode
						}
						this.beonList.push(pp)
					} else {
						let p = {
							getoffTime: k.signintime,
							getoffState: k.signstatus,
							signmode: k.signmode
						}
						this.getoList.push(p)
						// this.getoffTime = k.signintime
						// this.getoffState = k.signstatus
					}
				})
			},
			//改变年月
			changYearMonth(y, m) {
				this.dates = this.monthDay(y, m);
				this.y = y;
				this.m = m;
			},
			changeMonth(type) {
				if (type == 'pre') {
					if (this.m + 1 == 2) {
						this.m = 12;
						this.y = this.y - 1;
					} else {
						this.m = this.m - 1;
					}
				} else {
					if (this.m + 1 == 13) {
						this.m = 1;
						this.y = this.y + 1;
					} else {
						this.m = this.m + 1;
					}
				}
				this.dates = this.monthDay(this.y, this.m);
				// this.$emit('onMonth', this.formatNum(this.m));
				this.fun_GetSign_Info(this.formatNum(this.m));
			},
		},
		destroyed() {
			// wx.stopLocationUpdate(function(res) {
			// 	console.log('关闭了持续定位', res)
			// })
		},
	};
</script>

<style lang="scss" scoped>
	page {
		background-color: #fff;
	}

	.content {
		padding-top: 0rpx;

		.change {
			display: flex;
			align-items: center;
			justify-content: center;
			margin: 0 auto;
			margin-top: 50rpx;

			color: #333;

			.item {
				box-sizing: content-box;
				background-color: #36c0e5;
				width: 180px;
				height: 100rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				border-radius: 10px;
				margin: 0 20px;
				position: relative;
			}
		}
	}

	.time {
		padding: 12px 15px;
		color: #5f5f5f;

		view {
			padding: 5px 0;
		}
	}

	.calendar-wrapper {
		color: #bbb7b7;
		font-size: 28rpx;
		text-align: center;
		background-color: #fff;
		padding-bottom: 10rpx;

		.header {
			display: flex;
			align-items: center;
			justify-content: center;
			height: 88rpx;
			color: #42464A;
			font-size: 32rpx;
			font-weight: bold;
			border-bottom: 2rpx solid #f2f2f2;

			.pre,
			.next {
				color: #4d7df9;
				font-size: 28rpx;
				font-weight: normal;
				padding: 8rpx 15rpx;
				border-radius: 10rpx;
				border: 2rpx solid #dcdfe6;
			}

			.pre {
				margin-right: 30rpx;
			}

			.next {
				margin-left: 30rpx;
			}
		}

		.week {
			display: flex;
			align-items: center;
			height: 80rpx;
			line-height: 80rpx;
			border-bottom: 1rpx solid rgba(255, 255, 255, 0.2);

			view {
				flex: 1;
			}
		}

		.content {
			position: relative;
			overflow: hidden;
			transition: height 0.4s ease;
			padding: 10px 5px;
			padding-top: 0;

			.days {
				transition: top 0.3s;
				display: flex;
				align-items: center;
				flex-wrap: wrap;
				position: relative;

				.item {
					position: relative;
					display: block;
					height: 100rpx;
					line-height: 100rpx;
					width: calc(100% / 7);

					.day {
						position: relative;
						font-style: normal;
						display: inline-block;
						vertical-align: middle;
						width: 50rpx;
						height: 50rpx;
						line-height: 50rpx;
						overflow: hidden;
						border-radius: 60rpx;

						&.choose {
							background-color: #4d7df9;
							color: #fff;
						}

						&.nolm {
							color: #fff;
							opacity: 0.3;
						}
					}

					.isWorkDay {
						color: #42464a;
					}

					.notSigned {
						font-style: normal;
						width: 8rpx;
						height: 8rpx;
						background: #fa7268;
						border-radius: 10rpx;
						position: absolute;
						left: 50%;
						bottom: 0;
						pointer-events: none;
					}

					.today {
						color: #fff;
						background-color: #a8c0ff;
					}

					.workDay {
						font-style: normal;
						width: 8rpx;
						height: 8rpx;
						background: #4d7df9;
						border-radius: 10rpx;
						position: absolute;
						left: 50%;
						bottom: 0;
						pointer-events: none;
					}

					.markDay {
						font-style: normal;
						width: 8rpx;
						height: 8rpx;
						background: #fc7a64;
						border-radius: 10rpx;
						position: absolute;
						left: 50%;
						bottom: 0;
						pointer-events: none;
					}
				}
			}
		}

		.hide {
			height: 80rpx !important;
		}

		.weektoggle {
			width: 85rpx;
			height: 32rpx;
			position: relative;
			bottom: -42rpx;

			&.down {
				transform: rotate(180deg);
				bottom: 0;
			}
		}
	}

	.wenzi {
		width: 100%;
		position: absolute;
		left: 0;
		bottom: -22px;
		font-size: 10px;
		text-align: center;
		color: #38aa53;
	}

	.chuqing {
		color: #ffaa00;
	}

	.zhengchang {
		color: #38aa53;
	}

	.chidao {
		color: #a20000;
	}
</style>